import HandleBtn from '@/components/HandleBar/btn';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  historyDataControllerHistoryDataExport as exportDataReport,
  historyDataControllerPcsCtlOverviewPage,
} from '@/services/ess/historicalData';
import { downloadFetch } from '@/utils/downloadFile';
import { Link, useIntl } from '@umijs/max'; // 引入 useIntl
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import React, { useCallback, useEffect, useMemo, useState } from 'react';

interface Props {
  tabIndex?: string;
  deviceCode?: string;
  deviceType?: string;
  areaId?: string;
  selectedKeys?: string[];
}

const PCSControllerSummary: React.FC<Props> = ({
  deviceCode,
  deviceType,
  areaId,
  selectedKeys,
}) => {
  const intl = useIntl(); // 使用 useIntl 获取国际化函数

  const [data, setData] = useState<API.DeviceOverviewDTO[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [startDate, setStartDate] = useState(dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'));
  const [endDate, setEndDate] = useState(dayjs().format('YYYY-MM-DDTHH:mm:ss'));
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);

  const columns: ProColumns<any>[] = useMemo(
    () => [
      {
        title: intl.formatMessage({ id: 'data.s/N' }), // 使用 intl 替换
        key: 'index',
        valueType: 'index',
        width: 60,
        dataIndex: 'pageIndex',
      },
      {
        title: intl.formatMessage({ id: 'data.time' }), // 时间
        dataIndex: 'ts',
        key: 'ts',
        valueType: 'dateTimeRange',
        width: 200,
        initialValue: [dayjs().startOf('day'), dayjs()],
        render: (_, record) => {
          return <span>{record.ts}</span>; // 时间字段不需要替换
        },
        search: {
          transform: (value) => {
            return {
              startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
              endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            };
          },
          fieldProps: {
            onCalendarChange: (dates: [Dayjs, Dayjs]) => {
              if (dates && dates.length === 2) {
                const [start, end] = dates;
                if (dayjs(end).diff(start, 'day') > 31) {
                  message.warning(intl.formatMessage({ id: 'data.sDays' }));
                }
              }
            },
            disabledDate: (current: Dayjs | null) => {
              return current && current > dayjs().endOf('day');
            },
          },
        },
      },
      {
        title: intl.formatMessage({ id: 'data.numberOfOnline' }), // 在线数量
        dataIndex: 'onlineCount',
        key: 'onlineCount',
        hideInSearch: true,
        width: 150,
      },
      {
        title: intl.formatMessage({ id: 'data.numberOfOffline' }), // 离线数量
        dataIndex: 'offlineCount',
        key: 'offlineCount',
        hideInSearch: true,
        width: 150,
      },
      {
        title: intl.formatMessage({ id: 'data.numberOfStandby' }), // 待机数量
        dataIndex: 'standbyCount',
        key: 'standbyCount',
        hideInSearch: true,
        width: 150,
      },
      {
        title: intl.formatMessage({ id: 'data.numberOfRunning' }), // 运行数量
        dataIndex: 'runningCount',
        key: 'runningCount',
        hideInSearch: true,
        width: 150,
      },
      // {
      //   title: intl.formatMessage({ id: 'data.faults' }), // 故障数量
      //   dataIndex: 'faultCount',
      //   key: 'faultCount',
      //   hideInSearch: true,
      //   width: 150,
      // },
      // {
      //   title: intl.formatMessage({ id: 'data.numberOfOtherStates' }), // 故障数量
      //   dataIndex: 'otherNum',
      //   key: 'otherNum',
      //   hideInSearch: true,
      //   width: 150,
      // },
    ],
    [intl],
  );

  const fetchData = useCallback(async () => {
    setLoading(true);
    const response = await historyDataControllerPcsCtlOverviewPage({
      current,
      pageSize,
      startDate,
      endDate,
      deviceCode,
      deviceType,
      areaId,
    });

    if (response.success && response.data && response.data?.records) {
      setData(
        response.data.records.map((record, index) => ({
          pageIndex: (current - 1) * pageSize + index + 1,
          ts: record.ts,
          onlineCount: record.upNum,
          offlineCount: record.downNum,
          standbyCount: record.standbyNum,
          runningCount: record.runNum,
          faultCount: record.faultNum,
          otherNum: record.otherNum,
        })),
      );
      // @ts-ignore
      setTotal(response.data.total);
    } else {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
  }, [current, pageSize, startDate, endDate, deviceCode, deviceType, areaId]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleTableChange = useCallback((pagination: { current: number; pageSize: number }) => {
    setCurrent(pagination.current);
    setPageSize(pagination.pageSize);
  }, []);

  const handleSearch = useCallback((values: any) => {
    const startDate = dayjs(values.startDate);
    const endDate = dayjs(values.endDate);
    if (endDate.diff(startDate, 'day') > 31) {
      message.warning(intl.formatMessage({ id: 'data.sDays' }));
      return;
    }
    setStartDate(values.startDate);
    setEndDate(values.endDate);
  }, []);

  const handleReset = useCallback(() => {
    setCurrent(1);
    setPageSize(20);
    setStartDate(dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'));
    setEndDate(dayjs().format('YYYY-MM-DDTHH:mm:ss'));
    fetchData();
  }, [fetchData]);

  const scroll = {
    x: 1000, // 设置具体的宽度值
    y: 'calc(100vh - 300px)',
  };

  const columnToAttrMap: Record<string, string> = {
    ts: 'ts', // 时间
    onlineCount: 'upNum', // 在线数量
    offlineCount: 'downNum', // 离线数量
    standbyCount: 'standbyNum', // 待机数量
    runningCount: 'runNum', // 运行数量
    faultCount: 'faultNum', // 故障数量
    otherNum: 'otherNum', // 其他状态数量
  };

  const exportDataReportFun = async (params: any) => {
    const startDate = dayjs(params.startDate);
    const endDate = dayjs(params.endDate);
    if (endDate.diff(startDate, 'day') > 3) {
      message.warning(intl.formatMessage({ id: 'data.selectTimeRange' }));
      return;
    }

    const attrNames =
      selectedColumns.length > 0
        ? selectedColumns
            .filter((col) => col !== 'index' && col !== 'pageIndex')
            .map((col) => columnToAttrMap[col] || col)
        : Object.values(columnToAttrMap);

    const exportParams: API.HistoryDataQuery = {
      areaId: Number(areaId),
      deviceType,
      deviceCode,
      startDate: dayjs(params.startDate).format('YYYY-MM-DD HH:mm:ss'),
      endDate: dayjs(params.endDate).format('YYYY-MM-DD HH:mm:ss'),
      attrNames,
    };

    await downloadFetch(exportDataReport, exportParams);
  };

  return (
    <div>
      <ProTable
        headerTitle={intl.formatMessage({ id: 'data.pcsControllerOverview' })} // 使用 intl 替换
        search={{
          labelWidth: 80,
        }}
        columns={columns}
        scroll={scroll}
        pagination={{
          pageSize,
          total,
          onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
        }}
        dataSource={data}
        loading={loading}
        onSubmit={handleSearch}
        onReset={handleReset}
        columnsState={{
          value: Object.fromEntries(
            columns
              .filter((col) => col.dataIndex)
              .map((col) => [
                col.dataIndex,
                {
                  show:
                    selectedColumns.length === 0
                      ? true
                      : selectedColumns.includes(col.dataIndex as string),
                },
              ]),
          ),
          onChange: (stateMap) => {
            const newSelectedColumns = Object.entries(stateMap)
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              .filter(([_, value]) => value.show)
              .map(([key]) => key);
            setSelectedColumns(newSelectedColumns);
          },
          persistenceKey: 'pcs-controller-summary-columns',
          persistenceType: 'localStorage',
        }}
        toolbar={{
          className: 'historyToobalr',
          actions: [
            <>
              <HandleBtn
                key="export"
                handleType="export"
                onClick={() => exportDataReportFun(params)}
              >
                {intl.formatMessage({ id: 'statistics.common.export' })}
              </HandleBtn>
              <Link key="monitor" to={`/stationmonitor/realtime?key=${selectedKeys}`}>
                {intl.formatMessage({ id: 'data.realtimeMonitor' })}
              </Link>
            </>,
          ],
        }}
      />
    </div>
  );
};

export default PCSControllerSummary;
